/*
 * MIT License
 *
 * Copyright (c) 2020 wen.gu <454727014@qq.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

/***************************************************************************
 * Name: udp_session.cpp
 *
 * Purpose: udp socket session base API define and implementation
 *
 * Developer:
 *   wen.gu , 2023-11-01
 *
 * TODO:
 *
 ***************************************************************************/

#include "xbus/com/internal/udp_session.h"

#include "xbus/core/xtime.h"
#include "xbus/com/xmessage_impl.h"

#define GET_SEND_MSG_TIMEOUT_MS (10)
#define SOCK_RECV_TIMEOUT_MS (10)
#define UDP_RECV_BUF (2048)

namespace xbus::com::internal {
using namespace xbus::core;

UdpSession::~UdpSession() {
    /** todo something */
}

UdpSession::UdpSession(XSocketId sock_id, const std::string& session_name)
    :SockSession(sock_id, session_name),
    msg_parser_(UDP_MAX_PKT_SIZE, [this](XErrC err){
        //todo process error
    }) {
    /** todo something */
}

void UdpSession::onSendWorker() {
    while (is_running_) {
        auto msg_res = send_queue_->pop(GET_SEND_MSG_TIMEOUT_MS); 
        if (msg_res) {
            auto msg = msg_res.value();
            const auto& dst_ids = msg->msg_dst();

            if (msg->length() <= UDP_MAX_PKT_SIZE) {
                for (auto& dst_id: dst_ids) {
                    auto res = XSocketSend(session_id_, msg->data(), msg->length(), dst_id);
                    if (!res) {
                        //todo process error.
                        auto errc = res.error();
                        if (errc == XErrC::Disconnected) {

                        }
                    }                        
                }            
            } else {
                auto msg_list = msg->unpack(UDP_MAX_PKT_SIZE);

                for (auto& dst_id: dst_ids) {
                    for (auto& sub_msg: msg_list) {
                        auto res = XSocketSend(session_id_, sub_msg->data(), sub_msg->length(), dst_id);
                        if (!res) {
                            //todo process error.
                            auto errc = res.error();
                            if (errc == XErrC::Disconnected) {
                                
                            }
                        }                           
                    }
                }
            }
        } else {
            auto errc = msg_res.error();
            switch (errc) {
            case XErrC::InvalidStatus: 
                core::SleepMs(GET_SEND_MSG_TIMEOUT_MS);
                break;
            case XErrC::Disconnected:
                //todo process error
                break;
            default:
                break;
            }
        }
    }
}

void UdpSession::onRecvWorker() {
    uint8_t recv_buf[UDP_RECV_BUF];
    while (is_running_) {
        auto ret = XSocketRecv(session_id_, recv_buf, UDP_RECV_BUF, SOCK_RECV_TIMEOUT_MS);
        if (!ret) {
            auto errc = ret.error();
            if (errc == XErrC::Disconnected) {
                //todo process error
            } else if (errc == XErrC::TimeOut) {
                continue;
            }
            core::SleepMs(SOCK_RECV_TIMEOUT_MS);
            continue;
        }

        XSocketRecvResult res = ret.value();

        //printf("[%s.%d]====>:recv_size:%d err: %d, %s\n", __FUNCTION__, __LINE__, recv_size, errno, strerror(errno));

        printf("[%s.%d]====>:recv_size:%d\n", __FUNCTION__, __LINE__, res.recv_size);
        uint8_t* pdata = recv_buf;
        uint8_t* pend = recv_buf + res.recv_size;
        while (pdata < pend) {
            auto msg_ptr = msg_parser_.parse(pdata, pend);
            if (msg_ptr) {
                msg_ptr->set_msg_src(res.sock_id);
                auto ret = recv_queue_->push(msg_ptr);
                if (ret != XErrC::OK) {
                    //todo process the error ,e.g  the recv queue is full. now just discard it
                }
            }
        }
    }
}

} //namespace xbus::com::internal